package com.csun.dsms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.base.enums.ErrorCodeEnum;
import com.csun.dsms.comment.base.exception.BusinessException;
import com.csun.dsms.comment.config.properties.CsunProperties;
import com.csun.dsms.comment.core.support.BaseService;
import com.csun.dsms.comment.core.support.CsunMessageSource;
import com.csun.dsms.mapper.DsmsOpenUserMapper;
import com.csun.dsms.model.domain.DsmsOpenUser;
import com.csun.dsms.model.domain.DsmsStaff;
import com.csun.dsms.model.domain.DsmsUser;
import com.csun.dsms.model.dto.wechat.BindMobileDto;
import com.csun.dsms.model.dto.wechat.WeChatLoginDto;
import com.csun.dsms.model.entity.TokenModel;
import com.csun.dsms.model.vo.staff.StaffVo;
import com.csun.dsms.service.DsmsOpenUserService;
import com.csun.dsms.service.DsmsStaffService;
import com.csun.dsms.service.DsmsUserService;
import com.csun.dsms.service.TokenManager;
import com.csun.dsms.utils.PublicUtil;
import com.csun.dsms.utils.RedisUtil;
import com.csun.dsms.utils.wechat.WeChatUtil;
import com.csun.dsms.utils.wechat.WxUtils;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author chisj chisj@foxmail.com
 * @version 1.0.0
 * @date 2021-09-03 11:49
 * @description: TODO
 */
@Slf4j
@Service
@Transactional
public class DsmsOpenUserServiceImpl extends BaseService<DsmsOpenUser> implements DsmsOpenUserService {

    @Resource
    private DsmsOpenUserMapper dsmsOpenUserMapper;
    @Resource
    private TokenManager tokenManager;
    @Resource
    private CsunProperties csunProperties;
    @Resource
    private CsunMessageSource csunMessageSource;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private DsmsUserService dsmsUserService;
    @Resource
    private DsmsStaffService dsmsStaffService;

    @Override
    public Integer register(WeChatLoginDto weChatLoginDto, DsmsUser login) {

        DsmsUser dsmsUser = dsmsUserService.selectUserById(login.getId());
        if (PublicUtil.isEmpty(dsmsUser) || dsmsUser.getStatus().equals("DISABLE")) {
            throw new BusinessException(ErrorCodeEnum.GB10011052);  //该用户无登录权限
        }

        StaffVo staffVo = dsmsStaffService.selectByUserId(login.getId());
        if (PublicUtil.isEmpty(staffVo) || !staffVo.getApply().equals(1)) {
            throw new BusinessException(ErrorCodeEnum.GB10011052);
        }

        String result = getWechatSnsResult(weChatLoginDto);
        log.info("=====> login open id [{}]", result);

        // 转成Json对象 获取openid
        JSONObject jsonObject = JSONObject.parseObject(result);
        // 我们需要的openid，在一个小程序中，openid是唯一的
        String openid = jsonObject.get("openid").toString();
        String session_key = jsonObject.get("session_key").toString();

        DsmsOpenUser openUser = new DsmsOpenUser();
        openUser.setOpenId(openid);
        openUser = dsmsOpenUserMapper.selectOne(openUser);
        if (PublicUtil.isNotEmpty(openUser)) {
            throw new BusinessException(ErrorCodeEnum.GB10011037);
        }

        openUser = dsmsOpenUserMapper.selectByPrimaryKey(login.getId());
        if (PublicUtil.isNotEmpty(openUser)) {
            throw new BusinessException(ErrorCodeEnum.GB10011037);
        }

        // 新增用户
//        user.setAvatar(weChatLoginDto.getAvatar());
//        user.setUserName(weChatLoginDto.getNickName());
//        user.setUserSource(UserSourceEnum.REGISTER.getKey());
//        userMapper.insertSelective(user);
//
//        // 授权
//        RoleUser roleUser = new RoleUser();
//        roleUser.setUserId(user.getId());
//        roleUser.setRoleId(2l);
//        roleUserMapper.insertSelective(roleUser);
//
        openUser = new DsmsOpenUser();

        openUser.setOpenId(openid);
        openUser.setId(login.getId());
        openUser.setNickName(weChatLoginDto.getNickName());
        openUser.setGender(weChatLoginDto.getGender());
        openUser.setAvatar(weChatLoginDto.getAvatar());
        openUser.setCity(weChatLoginDto.getCity());
        openUser.setSessionKey(session_key);
        openUser.setUpdateInfo(login);

        return dsmsOpenUserMapper.insertSelective(openUser);
    }

    /**
     * 取消微信授权
     *
     * @param login
     *
     * @return  the int.
     */
    @Override
    public Integer unrRegister(DsmsUser login) {

        return dsmsOpenUserMapper.deleteByPrimaryKey(login.getId());
    }

    @Override
    public DsmsUser login(WeChatLoginDto weChatLoginDto) {

        String result = getWechatSnsResult(weChatLoginDto);
        log.info("=====> login open id [{}]", result);

        // 转成Json对象 获取openid
        JSONObject jsonObject = JSONObject.parseObject(result);
        // 我们需要的openid，在一个小程序中，openid是唯一的
        String openid = jsonObject.get("openid").toString();
        String session_key = jsonObject.get("session_key").toString();

        DsmsOpenUser openUser = new DsmsOpenUser();
        openUser.setOpenId(openid);
        openUser = dsmsOpenUserMapper.selectOne(openUser);
        if (PublicUtil.isEmpty(openUser)) {
            throw new BusinessException(ErrorCodeEnum.GB10011039);
        }

        DsmsUser dsmsUser = dsmsUserService.selectUserById(openUser.getId());
        if (PublicUtil.isEmpty(dsmsUser) || dsmsUser.getStatus().equals("DISABLE")) {
            throw new BusinessException(ErrorCodeEnum.GB10011052);
        }

        StaffVo staffVo = dsmsStaffService.selectByUserId(openUser.getId());
        if (PublicUtil.isEmpty(staffVo) || !staffVo.getApply().equals(1)) {
            throw new BusinessException(ErrorCodeEnum.GB10011052);
        }

        // 缓存 session_key
        redisUtil.set(dsmsUser.getId().toString(), session_key, -1);

        return dsmsUser;
    }

    @Override
    public Integer bindMobile(BindMobileDto bindMobileDto) {

        TokenModel model = tokenManager.getToken(bindMobileDto.getToken());

        String userId = model.getUserId().toString();
        String session_key = String.valueOf(redisUtil.get(userId));
        String encryptedData = bindMobileDto.getEncryptedData();
        String iv = bindMobileDto.getIv();

        try {
            String result = WxUtils.wxDecrypt(encryptedData, session_key, iv);
            log.info("====> chisj result [{}]", result);
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("phoneNumber")) {
                String phone = json.getString("phoneNumber");

                if (StringUtils.isNotBlank(phone)) {
                    //保存号码
                    DsmsUser user = new DsmsUser();
                    user.setId(model.getUserId());
                    user.setMobileNo(phone);
                    return dsmsUserService.update(user);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeEnum.GB10011038);
        }

        return 0;
    }

    public String getWechatSnsResult(WeChatLoginDto weChatLoginDto) {

        Preconditions.checkArgument(PublicUtil.isNotEmpty(weChatLoginDto.getCode()),
                csunMessageSource.getMessage("wechat.code.null", null));


        //txyun-wechat.properties 这个文件
        // 根据小程序传过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + csunProperties.getTxyun().getWechat().getAppId()
                + "&secret="
                + csunProperties.getTxyun().getWechat().getSecret()
                + "&js_code=" + weChatLoginDto.getCode()
                + "&grant_type=authorization_code";

        // 发送请求，返回Json字符串
        return  WeChatUtil.httpRequest(url, "GET", null);
    }

}
